package com.paradogs.framework.server;

import com.baidu.bjf.remoting.protobuf.annotation.ProtobufClass;
import com.paradogs.common.utils.ProtoUtils;
import io.netty.buffer.ByteBuf;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;

import java.io.IOException;
import java.util.Arrays;

/**
 * @author: yumi
 * @date: 2023/12/26  15:18
 * @Description: TODO
 */
@Data
@ProtobufClass
public class PRMessage {

    private MessageHeader header;

    private byte[] data;

    /**
     * 序列化（编码)
     * @param out
     */
    public void serialization(ByteBuf out) {

        // 字节消息特殊处理
        if (this.data instanceof byte[]) {
            out.writeBytes((byte[]) this.data);
            return;
        }
        // 写入消息体
        byte[] bytes = ProtoUtils.encode(this.data);

        out.writeBytes(bytes);

    }

    public void deserialization(ByteBuf in) throws IOException {
        // 读取消息体 byte 数组
        byte[] bytes = new byte[in.readableBytes()];
        in.readBytes(bytes);
        this.data = bytes;
    }

    @Override
    public String toString() {
        return "PRMessage{" +
                "header=" + header +
                ", data=" + Arrays.toString(data) +
                '}';
    }

    @Data
    @NoArgsConstructor
    @AllArgsConstructor
    public static class ServerData {
        private String channelId;
    }

}
